package controllers;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlUpdate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.*;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import static play.libs.Json.*;
/**
 * Created by duzi on 7/2/15.
 */
public class Search extends Controller{
    public Result search(){
        return ok(search.render());
    }

    public Result getCategorys(){
        List<Category> c = Category.find.all();
        return ok(toJson(c));
    }

    public Result getProducts(){
        List<Product> p = Product.find.all();
        return ok(toJson(p));
    }

    public Result getCustomers(){
        List<Customer> c = Customer.find.all();
        return ok(toJson(c));
    }

    public Result getUsers(){
        List<User> u = User.find.all();
        return ok(toJson(u));
    }

    public Result userNameInfo(String name){
        List<User> us = User.find.where().ilike("userName", "%" + name + "%").findList();
        if(us == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(us));
    }

    public Result productNameInfo(String name){
        List<Product> us = Product.find.where().ilike("productName", "%" + name + "%").findList();
        if(us == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(us));
    }
    public Result billItemInfo(Long id){
        List<BillItem> bIs = BillItem.find.where().ilike("billItemId", "%" + id + "%").findList();
        if(bIs == null){
            return badRequest("0");
        }

        return ok(toJson(bIs));
    }

    public Result categoryInfo(String name){
        List<Category> cs = Category.find.where().ilike("categoryName", "%" + name + "%").findList();
        if(cs == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(cs));
    }

    public  Result customerIdInfo(Long id){
       Customer c = Customer.find.byId(id);
        if(c == null){
            return ok("0");
        }
        return ok(toJson(c));
    }

    public Result customerNameInfo(String name){
        List<Customer> cs = Customer.find.where().ilike("name", "%" + name + "%").findList();
        if(cs == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(cs));
    }

    public Result billsCustomerTimeInfo(Long id, String start, String end){
        start = start + " 00:00:00";
        end = end + " 23:59:59";

        List<Bill> bs = Bill.find.where()
                .eq("customer_id", id)
                .ge("bill_createtime", transformDate(start))
                .le("bill_createtime", transformDate(end)).findList();
        if(bs.size() == 0){
            return ok("0");
        }

        return ok(toJson(bs));
    }

    public Result userInfo(Long id){
        User user = User.findById(id);

        if(user == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(user));
    }

    public Result billsPeriodInfo(String name, String start, String end){
        start = start + " 00:00:00";
        end = end + " 23:59:59";

        Category c = Category.find.where().eq("category_name", name).findUnique();

        if(c == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        Long cId = c.categoryId;

        List<BillItem> billItems = BillItem.find.where()
                                                .eq("bill_item_status", "1")
                                                .ge("bill_item_createtime", transformDate(start))
                                                .le("bill_item_createtime", transformDate(end))
                                                .findList();

        List<BillItem> resultItems = new ArrayList<>();
        float sumPrice = 0.0f;
        int amount = 0;
        for(BillItem item : billItems){
            if(item.product.category.categoryId == cId){
                resultItems.add(item);
                sumPrice += Double.parseDouble(item.billItemSumPrice);
                amount += item.billItemSum;
            }
        }

        ObjectNode res = Json.newObject();
        res.put("categoryId", cId);
        res.put("name", name);
        res.put("amount", amount);
        res.put("sumPrice", sumPrice);
        res.put("items", toJson(resultItems));

        return ok(res);
    }

    public Date transformDate(String a){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date d;

        try{
            d = sdf.parse(a);
        }catch (java.text.ParseException ex){
            System.out.println("wrong date format");
            return null;
        }

        return d;
    }

    public Result getBillItemInfo(Long id){
        BillItem b = BillItem.find.byId(id);

        if(b == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        return ok(toJson(b));
    }

    public Result changeAttrByRaw(){
        JsonNode data = request().body().asJson();
        Long id = data.get("id").asLong();
        String key = data.get("key").asText();
        String value = data.get("value").asText();
        String table = data.get("table").asText();

        String s = "UPDATE " + table + " set " + key + " = :key where "+ table+"_id = :id";
        SqlUpdate update = Ebean.createSqlUpdate(s);
        update.setParameter("id", id);
        update.setParameter("key", value);

        Ebean.execute(update);

        return ok("");
    }

    @BodyParser.Of(BodyParser.Json.class)
    public Result delProducts(){
       JsonNode  data= request().body().asJson();
       Long id = data.get("id").asLong();
       Product p = Product.find.byId(id);

        if(p == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }
        p.category = null;
        p.supplier =null;
        p.update();
        p.delete();

        return ok("");
    }

    @BodyParser.Of(BodyParser.Json.class)
    public Result delCategorys(){
        JsonNode  data= request().body().asJson();
        Long id = data.get("id").asLong();
        Category p = Category.find.byId(id);

        if(p == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }
        p.products = null;
        p.update();
        p.delete();

        return ok("");
    }

    @BodyParser.Of(BodyParser.Json.class)
    public Result delCustomers(){
        JsonNode  data= request().body().asJson();
        Long id = data.get("id").asLong();
        Customer p = Customer.find.byId(id);

        if(p == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        p.bill = null;
        p.update();
        p.delete();

        return ok("");
    }

    @BodyParser.Of(BodyParser.Json.class)
    public Result delUsers(){
        JsonNode  data= request().body().asJson();
        Long id = data.get("id").asLong();
        User p = User.find.byId(id);

        if(p == null){
            ObjectNode err = Json.newObject();
            err.put("code",0);
            err.put("errorMsg", "not found");
            return ok(err);
        }

        p.delete();

        return ok("");
    }

    public Result createCustomer(){
        Customer c = new Customer();
        c.save();

        return ok(toJson(c.customerId));
    };

    public Result createProduct(){
        Product c = new Product();
        c.save();

        return ok(toJson(c.productId));
    };

    public Result createCategory(){
        Category c = new Category();
        c.save();

        return ok(toJson(c.categoryId));
    };

    public Result createUser(){
        User c = new User();
        c.save();

        return ok(toJson(c.userId));
    };
}
